﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net 管理页面控制器        ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                    ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone               ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using Wedn.Net.Common;
using Wedn.Net.Controller.Base;
using Wedn.Net.Model;
using Wedn.Net.Utility;

namespace Wedn.Net.Admin.Controllers
{
    /// <summary>
    /// 管理页面控制器
    /// </summary>
    public class Admin1Controller : AdminBaseController
    {
        /// <summary>
        /// 管理页面首页框架
        /// </summary>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 管理页面首页
        /// </summary>
        public ActionResult Welcome()
        {
            return View();
        }

        #region Term

        /// <summary>
        /// 标签管理页面
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult Term(string type)//, string action)
        {
            //权限校验
            if (CurrentUser.Role < (short)UserRole.Writer) return Redirect(Url.Action("Index", "Login"));
            IList<Term> list = null;
            switch (type)
            {
                default:
                case "post_category":
                    ViewBag.Title = "分类目录";
                    ViewBag.Type = (int)TermType.PostCategory;
                    list = BllInstance.TermManager.Select(c => c.Type == (int)TermType.PostCategory).ToList();
                    IList<Term> postCategorys = new List<Term>();
                    BllInstance.TermManager.LoadTierCategoryList(list, postCategorys, "─", 0);
                    ViewBag.Terms = postCategorys;
                    break;
                case "post_tag":
                    ViewBag.Title = "标签";
                    ViewBag.Type = (int)TermType.PostTag;
                    list = BLLFactory.BLLFactory.Instance.TermManager.Select(c => c.Type == (int)TermType.PostTag).ToList();
                    ViewBag.Terms = list;
                    break;
                case "link_category":
                    ViewBag.Title = "链接分类目录";
                    ViewBag.Type = (int)TermType.LinkCategory;
                    list = BllInstance.TermManager.Select(c => c.Type == (int)TermType.LinkCategory).ToList();
                    IList<Term> linkCategorys = new List<Term>();
                    BllInstance.TermManager.LoadTierCategoryList(list, linkCategorys, "─", 0);
                    ViewBag.Terms = linkCategorys;
                    break;
            }
            return View();
        }

        ///// <summary>
        ///// 所有分类
        ///// </summary>
        //public ActionResult Categorys()
        //{
        //    //权限校验
        //    if (CurrentUser.Role < (short)UserRole.Writer) return Redirect(Url.Action("Index", "Login"));

        //    var list = BllInstance.TermManager.Select(c => c.Type == (int)TermType.PostCategory).ToList();
        //    IList<Term> categorys = new List<Term>();
        //    BllInstance.TermManager.LoadTierCategoryList(list, categorys, "─", 0);
        //    //list.Sort();
        //    return View(categorys);
        //}

        ///// <summary>
        ///// 所有标签
        ///// </summary>
        //public ActionResult Tags()
        //{
        //    //权限校验
        //    if (CurrentUser.Role < (short)UserRole.Writer) return Redirect(Url.Action("Index", "Login"));

        //    var tags = BLLFactory.BLLFactory.Instance.TermManager.Select(c => c.Type == (int)TermType.PostTag).ToList();
        //    return View(tags);
        //}

        #endregion

        #region Post

        /// <summary>
        /// 所有文章
        /// </summary>
        public ActionResult Post(string type)
        {
            if (CurrentUser.Role < (short)UserRole.Writer) return Redirect(Url.Action("Index", "Login"));//权限校验

            int pageSize = 20;
            PostType postType = PostType.Article;
            //取标签集合
            var terms = BllInstance.TermManager.Select(t => true).ToList();

            ViewBag.Type = string.IsNullOrEmpty(type) ? "post" : type;
            ViewBag.Title = "所有文章";
            if (type == "page")
            {
                postType = PostType.Page;
                ViewBag.Title = "所有页面";
            }
            else
            {
                //格式化类别信息
                IList<Term> formatCategorys = new List<Term>();
                BllInstance.TermManager.LoadTierCategoryList(terms.Where(c => c.Type == (int)TermType.PostCategory).ToList(), formatCategorys, "─", 0);
                ViewBag.FormatCategorys = formatCategorys;
            }
            //关系信息实体集合
            var relations = BllInstance.RelationManager.Select(r => r.ObjectType == (int)RelationObjectType.Post).ToList();
            //取主体信息数据集合
            int totalCount;
            var posts = BllInstance.PostManager.SelectPage(1, pageSize, out totalCount,
                p =>
                p.Type == (int)postType &&
                p.Status == (int)PostStatus.Pubilc,
                p => p.Modified, true
                ).ToList();
            foreach (var item in posts)
            {
                var rIds = relations.Where(r => r.ObjectId == item.Id).Select(r => r.TermId).ToArray();
                var itemTerms = terms.Where(t => rIds.Contains(t.Id));
                //item.Link = Wedn.Net.UI.Url.Post(item.Slug);
                //item.Author = users.FirstOrDefault(u => u.Id == item.UserId).NickName;
                //item.Categorys = string.Join("、", itemTerms.Where(c => c.Type == (short)TermType.PostCategory).Select(c => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", UI.Url.Category(!string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name), c.Name)));
                //item.Tags = string.Join("、", itemTerms.Where(c => c.Type == (short)TermType.PostTag).Select(c => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", UI.Url.Tag(!string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name), c.Name)));
            }
            //往视图包存放数据
            ViewBag.Terms = terms;
            ViewBag.Relations = relations;
            ViewBag.TotalCount = totalCount;
            ViewBag.TotalPage = Math.Ceiling(ViewBag.TotalCount / (double)pageSize);
            ViewBag.Posts = posts;
            return View();
            #region Old
            //var terms = BllInstance.TermManager.Select(t => true).ToList();
            //IList<Term> formatCategorys = new List<Term>();
            //BllInstance.TermManager.LoadTierCategoryList(terms.Where(c => c.Type == (int)TermType.PostCategory).ToList(), formatCategorys, "─", 0);

            //ViewBag.Terms = terms;
            //ViewBag.FormatCategorys = formatCategorys;

            //int totalCount;
            //var posts = BllInstance.PostManager.SelectPage(1, 30, out totalCount,
            //    p =>
            //    p.Type == (int)PostType.Article &&
            //    p.Status == (int)PostStatus.Pubilc,
            //    p => p.Modified, true
            //    ).ToList();
            //var relations = BllInstance.RelationManager.Select(r => r.ObjectType == (int)RelationObjectType.Post).ToList();
            //foreach (var item in posts)
            //{
            //    var rIds = relations.Where(r => r.ObjectId == item.Id).Select(r => r.TermId).ToArray();
            //    var itemTerms = terms.Where(t => rIds.Contains(t.Id));
            //    item.Link = Wedn.Net.UI.Url.Post(item.Slug);
            //    //item.Author = users.FirstOrDefault(u => u.Id == item.UserId).NickName;
            //    item.Categorys = string.Join("、", itemTerms.Where(c => c.Type == (short)TermType.PostCategory).Select(c => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", UI.Url.Category(!string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name), c.Name)));
            //    item.Tags = string.Join("、", itemTerms.Where(c => c.Type == (short)TermType.PostTag).Select(c => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", UI.Url.Tag(!string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name), c.Name)));
            //}
            //ViewBag.Relations = relations;
            //ViewBag.TotalCount = totalCount;
            //ViewBag.TotalPage = Math.Ceiling(ViewBag.TotalCount / (double)30);
            //return View(posts); 
            #endregion
        }

        /// <summary>
        /// 撰写新文章
        /// </summary>
        public ActionResult Writer()
        {
            //权限校验
            if (CurrentUser.Role < (short)UserRole.Writer) return Redirect(Url.Action("Index", "Login"));

            var terms = BllInstance.TermManager.Select(c => c.Type == (int)TermType.PostCategory).ToList();
            IList<Term> categorys = new List<Term>();
            BllInstance.TermManager.LoadTierCategoryList(terms, categorys, "--", 0);
            ViewBag.Categorys = categorys;
            ViewBag.PopCategorys = terms.OrderByDescending(c => c.Count).Take(10).ToList();
            ViewBag.Authors = BllInstance.UserManager.Select(u => u.Status == (int)UserStatus.Normal && u.Role > (int)UserRole.Subscriber).ToList();
            ViewBag.CurrentUser = CurrentUser;
            return View();
        }

        /// <summary>
        /// 编辑文章
        /// </summary>
        public ActionResult Editor()
        {
            //权限校验
            if (CurrentUser.Role < (short)UserRole.Writer) return Redirect(Url.Action("Index", "Login"));

            int postId = RequestHelper.QueryInt("post", -1);
            if (postId == -1)
                RedirectToAction("Writer");
            var post = BllInstance.PostManager.SelectSingle(p => p.Id == postId);
            IList<Term> terms = BllInstance.TermManager.Select(c => true).ToList();
            IList<Term> categorys = terms.Where(c => c.Type == (int)TermType.PostCategory).ToList();
            IList<Term> tags = terms.Where(c => c.Type == (int)TermType.PostTag).ToList();
            IList<Term> formatCategorys = new List<Term>();
            BllInstance.TermManager.LoadTierCategoryList(categorys, formatCategorys, "--", 0);

            ViewBag.Relations = BllInstance.RelationManager.Select(r => r.ObjectId == postId && r.ObjectType == (int)RelationObjectType.Post).ToList();
            ViewBag.Tags = tags;
            ViewBag.Categorys = formatCategorys;
            ViewBag.PopCategorys = categorys.OrderByDescending(c => c.Count).Take(10).ToList();
            ViewBag.Authors = BllInstance.UserManager.Select(u => u.Status == (int)UserStatus.Normal && u.Role > (int)UserRole.Subscriber).ToList();
            ViewBag.CurrentPost = post;
            return View();
        }

        #endregion

        #region Media

        /// <summary>
        /// 媒体管理
        /// </summary>
        public ActionResult Media()
        {
            return View();
        }

        #endregion

        #region Link
        /// <summary>
        /// 链接管理页
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public ActionResult Link(string action)
        {
            if ("new" != action)
            {

            }
            else
            {

            }
            return View();
        }

        #endregion

        #region Tool

        /// <summary>
        /// 可用工具
        /// </summary>
        /// <returns></returns>
        public ActionResult Tool()
        {
            return View();
        }

        /// <summary>
        /// 可用工具
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Tool(int? source, HttpPostedFileBase attachment)
        {
            XDocument xDoc = XDocument.Load(attachment.InputStream);
            var xRoot = xDoc.Root;
            XNamespace cont = "http://purl.org/rss/1.0/modules/content/";
            XNamespace wfw = "http://wellformedweb.org/CommentAPI/";
            XNamespace dc = "http://purl.org/dc/elements/1.1/";
            XNamespace excer = "http://wordpress.org/export/1.2/excerpt/";
            XNamespace wp = "http://wordpress.org/export/1.2/";
            if (xRoot != null)
            {
                var list = xRoot.Element("channel").Elements("item");
                foreach (var item in list)
                {
                    var title = item.Element("title").Value;
                    var postDate = item.Element(wp + "post_date").Value;
                    var slug = item.Element(wp + "post_name").Value;
                    var pubDate = item.Element(wp + "post_date").Value;
                    var author = item.Element(dc + "creator").Value;
                    var excerpt = item.Element(excer + "encoded").Value;
                    var content = item.Element(cont + "encoded").Value;
                    var password = item.Element(wp + "post_password").Value;
                    var type = (short)(item.Element(wp + "post_type").Value == "post" ? 0 : 1);
                    IEnumerable<XElement> xmlTerms=item.Elements("category");
                    var tag = string.Join(",", xmlTerms.Where(t => t.Attribute("domain").Value == "post_tag").Select(i => i.Value));
                
                    #region 处理发表物
                    Post entity = new Post();
                    entity.UserId = 1;
                    entity.Slug = slug;
                    entity.Title = title;
                    entity.PubDate = pubDate.ToDataTime(DateTime.Now);
                    entity.Modified = entity.PubDate;
                    entity.Content = content;
                    entity.Excerpt = excerpt;
                    entity.Type = type;
                    entity.IsTop = false;
                    entity.Status = 0;
                    entity.CommentStatus = 0;
                    entity.PingStatus = 0;
                    entity.Pinged = string.Empty;
                    entity.Password = password;
                    BllInstance.PostManager.Insert(entity);//向数据库上下文插入文章实体
                    //更新文章数
                    BllInstance.OptionManager.UpdateValue("site_post_count", (Setting.SitePostCount + 1).ToString());

                    int rows = BllInstance.DbSaveChanges();//同步数据库上下文变化到数据库 
                    #endregion

                    //创建关系对象集合
                    var relations = new List<Relation>();
                    var terms = BllInstance.TermManager.Select(t => true).ToList();

                    #region 处理标签
                    //string tag = RequestHelper.FormString("post_tag");
                    if (!string.IsNullOrEmpty(tag))
                    {
                        string[] tags = tag.Split(new[] { ',', '|', '，' }, StringSplitOptions.RemoveEmptyEntries);
                        //获取已存在的标签数据
                        IList<Term> existTags = terms.Where(t => t.Type == (int)TermType.PostTag && tags.Contains(t.Name)).ToList();
                        IList<int> tagIds = new List<int>();//existTags.Select(t => t.Id).ToList();
                        IList<string> existTagsName = new List<string>(); //existTags.Select(t => t.Name).ToArray();
                        //更新标签文章数量
                        foreach (var t in existTags)
                        {
                            t.Count++;
                            tagIds.Add(t.Id);
                            existTagsName.Add(t.Name);
                            BllInstance.TermManager.Update(t);//更新文章数
                        }
                        //创建新标签集合
                        IList<Term> newTags = tags.Where(t => !existTagsName.Contains(t))
                            .Select(t => new Term { Name = t, Description = string.Empty, ParentId = -1, Slug = string.Empty, Count = 1 })
                            .ToList();
                        BllInstance.TermManager.Insert(newTags.ToArray());//向数据库上下文插入标签实体
                        rows += BllInstance.DbSaveChanges();//同步数据库上下文变化到数据库
                        foreach (var t in newTags)
                        {
                            tagIds.Add(t.Id);
                        }
                        relations.AddRange(tagIds.Select(i => new Relation { ObjectId = entity.Id, ObjectType = (int)RelationObjectType.Post, TermId = i }).ToList());
                        //更新标签数
                        BllInstance.OptionManager.UpdateValue("site_tag_count", (Setting.SiteTagCount + newTags.Count).ToString());
                    }
                    #endregion


                    //保存关系
                    if (relations.Count > 0)
                    {
                        var delRel = BllInstance.RelationManager.Select(r => r.ObjectId == entity.Id && r.ObjectType == (int)RelationObjectType.Post);
                        foreach (var rel in delRel)
                        {
                            Term term = terms.FirstOrDefault(t => t.Id == rel.TermId);
                            term.Count--;
                            BllInstance.TermManager.Update(term);
                            BllInstance.RelationManager.Delete(rel);
                        }
                        foreach (var rel in relations)
                            BllInstance.RelationManager.Insert(rel);//向数据库上下文插入关系实体
                        rows += BllInstance.DbSaveChanges();//同步数据库上下文变化到数据库 
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }

            #region MyRegion
            //string data = string.Format("post_author={0}&post_slug={1}&post_title={2}&post_pubdate={3}&post_modified={4}&post_content={5}&post_excerpt={6}&post_type={7}&post_istop={8}&post_status={9}&post_comment_status={10}&post_ping_status={11}&post_password={12}",
            //    1,
            //    slug,
            //    title,
            //    pubDate,
            //    pubDate,
            //    content,
            //    excerpt,
            //    type,
            //    "false",
            //    0,
            //    0,
            //    0,
            //    password);
            //HttpHelper.Post(Config.SiteUrl + "handlers/postAjax.ashx?action=publish", data);
            //System.IO.StreamReader srd=new System.IO.StreamReader(attachment.InputStream);
            //var rss = srd.ReadToEnd();
            //XmlDocument rssDoc = new XmlDocument();
            //rssDoc.Load(attachment.InputStream);
            //var rssNodes = rssDoc.ChildNodes;
            //System.Xml.XmlNamespaceManager nsmanager = new System.Xml.XmlNamespaceManager(rssDoc.NameTable);
            //nsmanager.AddNamespace("wp", "http://search.yahoo.com/mrss/");
            //nsmanager.AddNamespace("excerpt", "http://search.yahoo.com/mrss/");
            //nsmanager.AddNamespace("content", "http://search.yahoo.com/mrss/"); 
            //var itemNodes = rssDoc.SelectNodes("rss/channel/item");

            //foreach (XmlNode item in itemNodes)
            //{
            //    //var slug= item.SelectSingleNode("wp\:post_name").InnerText;
            //    var title = item.SelectSingleNode("title").InnerText;
            //    var pubDate = item.SelectSingleNode("wp:post_date",nsmanager).InnerText.ToDataTime();
            //    //var author = item.SelectSingleNode("dc\\:creator").InnerText;
            //    var excerpt = item.SelectSingleNode("excerpt:encoded", nsmanager).InnerText;
            //    var content = item.SelectSingleNode("content:encoded", nsmanager).InnerText;
            //    var password = item.SelectSingleNode("wp:post_password", nsmanager).InnerText;
            //    var type = item.SelectSingleNode("wp:post_type", nsmanager).InnerText == "post" ? 0 : 1;
            //    string data=string.Format("post_author={0}&post_slug={1}&post_title={2}&post_pubdate={3}&post_modified={4}&post_content={5}&post_excerpt={6}&post_type={7}&post_istop={8}&post_status={9}&post_comment_status={10}&post_ping_status={11}&post_password={12}",
            //        1,
            //        "",
            //        title,
            //        pubDate,
            //        pubDate,
            //        content,
            //        excerpt,
            //        type,
            //        "false",
            //        0,
            //        0,
            //        0,
            //        password);
            //    HttpHelper.Post(Config.SiteUrl + "handlers/postAjax.ashx?action=publish", data);
            //    System.Threading.Thread.Sleep(100);
            //} 
            #endregion

            return View();
        }
        //public ActionResult Import()
        //{
        //    return View();
        //}

        //public ActionResult Export()
        //{
        //    return View();
        //}

        #endregion

        #region Option

        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Option()
        {
            //权限校验
            if (CurrentUser.Role < (short)UserRole.Writer) return Redirect(Url.Action("Index", "Login"));

            string anchor = RequestHelper.QueryString("go");
            switch (anchor)
            {
                case "route":
                    ViewBag.RouteContent = System.IO.File.ReadAllText(Server.MapPath("/config/route.config"), Encoding.UTF8);
                    break;
            }
            return View();
        }

        #endregion



        #region Login
        ///// <summary>
        ///// 用户登录
        ///// </summary>
        //public ActionResult Login()
        //{
        //    //User CurrentUser = Session["CurrentUser"] as User;
        //    //if (CurrentUser != null)
        //    //{
        //    //    //string redirectTo = RequestHelper.QueryString("r");
        //    //    if (string.IsNullOrEmpty(redirect))
        //    //        redirect = "/";
        //    //    return RedirectToAction("Index");
        //    //}

        //    return View();
        //} 
        #endregion
    }
}
